import axios from 'axios';
import properties from '@/properties.js';
import { formatResponse } from './string';

axios.defaults.withCredentials = true;
axios.defaults.baseURL = properties.$baseURL + '/api/';

const post = ({url, data, name}) => {
  if(url.startsWith('/')) url = url.slice(1);
  console.log(`posting ${name}`, url, data);
	let formData = new FormData();
	Object.keys(data).forEach(key => {
		formData.append(key, data[key]);
	})
  return new Promise((resolve, reject) => {
    new axios({
      url,
      method: 'POST',
      data: formData
    }).then(res => {
      if(res.data.success) {
        formatResponse(res.data.object);
        console.log(`post ${name} success`, res.data);
      } else {
        console.warn(`post ${name} fail`, res.data);
      }
      resolve(res);
    }).catch(error => {
      console.error(`post ${name} error`, error);
      reject(error);
    })
  })
}

const fetch = ({url, method, data, name}) => {
  if(url.startsWith('/')) url = url.slice(1);
  console.log(`fetching ${name}`, url, data);
	if(method === 'POST') {
    let formData = new FormData();
    Object.keys(data).forEach(key => {
      formData.append(key, data[key]);
    })
    return new Promise((resolve, reject) => {
      new axios({
        url,
        method: 'POST',
        data: formData
      }).then(res => {
        if(res.data.success) {
          formatResponse(res.data.object);
          console.log(`fetch ${name} success`, res.data);
        } else {
          console.warn(`fetch $${name} fail`, res.data);
        }
        resolve(res);
      }).catch(error => {
        console.error(`fetch ${name} error`, error);
        reject(error);
      })
    })
  } else {
    return new Promise((resolve, reject) => {
      new axios({
        url,
        method: 'GET'
      }).then(res => {
        if(res.data.success) {
          formatResponse(res.data.object);
          console.log(`fetch ${name} success`, res.data);
        } else {
          console.warn(`fetch $${name} fail`, res.data);
        }
        resolve(res);
      }).catch(error => {
        console.error(`fetch ${name} error`, error);
        reject(error);
      })
    })
  }
}

const get = ({url, params, name, responseType}) => {
  if(url.startsWith('/')) url = url.slice(1);
  console.log(`getting ${name}`, url, params);
  return new Promise((resolve, reject) => {
    new axios({
      url,
      method: 'GET',
      params,
      responseType
    }).then(res => {
      if(res.data.success) {
        console.log(`get ${name} success`, res.data);
        formatResponse(res.data.object);
      }
      else {
        console.warn(`get ${name} fail`, res.data);
      }
      resolve(res);
    }).catch(error => {
      console.error(`get ${name} error`, error);
      reject(error);
    })
  })
}

export {
  post,
  get,
  fetch
}